<template>
  <div>
    <el-button :icon="DArrowLeft" type="primary" @click="router.back()">返回</el-button>
    <el-button type="primary" @click="addModule">添加模块</el-button>
    <el-table ref="dragTable" :data="tableData" style="height: calc(100vh - 230px)">
      <el-table-column width="30" align="center">
        <template #default="scope">
          <i class="icon-handle">
            <el-icon>
              <DCaret />
            </el-icon>
          </i>
        </template>
      </el-table-column>
      <el-table-column prop="moduleName" label="模块名称" />
      <el-table-column prop="type" label="模块类型" align="center" />
      <el-table-column prop="name" label="状态" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-text="开启"
            inactive-text="关闭" inline-prompt @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="seq" label="排序" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link v-for="(item, index) in incidentList" :key="index" :type="item.type"
            @click="handleChose(scope.row, index)">{{ item.title }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :limit="searchFrom.pageSize" :page="searchFrom.pageNum" @pagination="handlePageChange">
    </Pagination>
    <WebBrand :listItem="publicItem" :brandDrawer="brandDrawer" :websiteId="route.query.id"
      :languageId="route.query.languageId" @handleBrandClose="handleBrandClose"></WebBrand>
    <WebCard :listItem="publicItem" :cardDrawer="cardDrawer" :websiteId="route.query.id"
      :languageId="route.query.languageId" @handleCardVisibleClose="handleCardVisibleClose"></WebCard>

    <WebProduct :listItem="publicItem" :productDrawer="productDrawer" :websiteId="route.query.id"
      @handleProductVisibleClose="handleProductVisibleClose"></WebProduct>

    <WebCarousel :listItem="publicItem" :carouselDrawer="carouselDrawer" :websiteId="route.query.id"
      @handleCarouselVisibleClose="handleCarouselVisibleClose"></WebCarousel>

    <WebCustom :websiteId="route.query.id" :listItem="publicItem" :customDrawer="customDrawer"
      @handleCustomVisibleClose="handleCustomVisibleClose"></WebCustom>

    <WebCategory :listItem="publicItem" :categoryDrawer="categoryDrawer" :websiteId="route.query.id"
      :languageId="route.query.languageId" @handleCategoryVisibleClose="handleCategoryVisibleClose"></WebCategory>

    <el-dialog v-model="dialogVisible" title="模块" width="600" :before-close="handleClose">
      <el-form :inline="true" :model="modalForm" label-width="auto" ref="moduleFormRef" :rules="rules"
        label-position="left">
        <el-form-item label="模块名称" prop="moduleName" style="width: 100%" required>
          <el-input v-model.trim="modalForm.moduleName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="模块类型" style="width: 100%" prop="moduleType" required>
          <el-select v-model="modalForm.moduleType" placeholder="请选择" @change="handleModuleType"
            :disabled="disabledType">
            <el-option v-for="dict in sys_module_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模块状态" style="width: 100%" prop="status" required>
          <el-switch v-model="modalForm.status" :active-value="1" :inactive-value="0" active-text="开启"
            inactive-text="关闭" inline-prompt />
        </el-form-item>
        <el-form-item style="width: 100%" v-show="showLanguage">
          <MoreLanguage :newList="modalForm.descriptions" label="主题名称" :showControls="true" :showRemark="showRemark">
          </MoreLanguage>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleModule"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { DArrowLeft, DCaret } from "@element-plus/icons-vue";
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import WebBrand from "./web/webBrand.vue";
import WebCard from "./web/webCard.vue";
import WebCarousel from "./web/webCarousel.vue";
import WebProduct from "./web/webProduct.vue";
import WebCustom from "./web/webCustom.vue";
import WebCategory from "./web/webCategory.vue";


const { proxy } = getCurrentInstance();
const { sys_module_type } = proxy.useDict("sys_module_type");

const router = useRouter();
const route = useRoute();
const total = ref(0);

const publicItem = ref({}); //公共赋值对象数据
const tableData = ref([]);
const brandDrawer = ref(false); //默认轮播false
const cardDrawer = ref(false); //默认卡片链接false
const productDrawer = ref(false); //默认商品分组false
const carouselDrawer = ref(false); //默认品牌推荐false
const customDrawer = ref(false); //自定义模块false
const categoryDrawer = ref(false); //推荐分类false


const dialogVisible = ref(false); //默认添加模块false
const Judgment = ref(false); //防止列表调用status时报错
const showRemark = ref(false); //默认语言没有描述
const showLanguage = ref(false); //默认不显示语言
const disabledType = ref(false); //默认可以选择模块类型

const searchFrom = ref({
  pageNum: 1,
  pageSize: 20,
  param: {
    websiteId: null,
  },
});
// 模块参数
const modalForm = ref({
  moduleName: "", //模块名称
  websiteId: null,
  status: 1,
  moduleType: "Banner", //模块类型
  descriptions: [], //多语言
});
onMounted(() => {
  getList();
  handleDrag()
});
const getList = () => {
  searchFrom.value.param.websiteId = Number(route.query.id);
  site.module
    .sitewebsitemoduleList({
      data: searchFrom.value,
    })
    .then((res) => {
      Judgment.value = true;
      total.value = res.total;
      if (res.data?.length) {
        res.data = res.data.map((item) => {
          return {
            ...item,
            type: sys_module_type.value.find((e) => e.value === item.moduleType)
              ?.label,
          };
        });
      }
      tableData.value = res.data;
    })
};
const handleChose = (row, index) => {
  if (index === 1) {
    publicItem.value = row;
    handleCommand(row);
  } else if (index === 2) {
    var newArray = [];
    newArray.push(row.id);
    proxy.$modal
      .confirm("是否确认删除此数据项？")
      .then(() => {
        site.module
          .sitewebsitemoduleDeletebatch({
            data: {
              ids: newArray,
            },
          })
          .then((res) => {
            if (res.code !== 200) return;
            proxy.$modal.msgSuccess("删除成功");
            getList();
          });
      })
      .catch(() => { });
  } else {
    publicItem.value = row;
    site.module
      .sitewebsitemoduleGetbyid({
        pathParams: {
          id: row.id,
        },
      })
      .then((res) => {
        modalForm.value.descriptions = [];
        disabledType.value = true;
        dialogVisible.value = true;
        modalForm.value.moduleName = res.data.moduleName;
        modalForm.value.websiteId = res.data.websiteId;
        modalForm.value.status = res.data.status;
        modalForm.value.moduleType = res.data.moduleType;
        if (res.data.moduleType !== "Banner" && res.data.moduleType !== 'Custom') {
          showLanguage.value = true;
        } else {
          showLanguage.value = false;
        }

        if (res.data.moduleType === "Card" || res.data.moduleType === "Brand") {
          showRemark.value = true;
        } else {
          showRemark.value = false;
        }

        res.data.descriptions?.forEach((e) => {
          modalForm.value.descriptions.push({
            languageId: e.languageId,
            name: e.name,
            description: e.description,
          });
        });
        // modalForm.value.descriptions=res.data.moduleName;

        console.log(res.data, "获取详细信息");
      });
  }
};

// 跳转选项
const handleCommand = (row) => {
  console.log('441414141');
  if (row.moduleType === "Banner") {
    brandDrawer.value = true;
  } else if (row.moduleType === "Card") {
    cardDrawer.value = true;
  } else if (row.moduleType === "Product") {
    productDrawer.value = true;
  } else if (row.moduleType === "Brand") {
    carouselDrawer.value = true;
  } else if (row.moduleType === "Category") {//推荐分类
    categoryDrawer.value = true;
  } else {
    customDrawer.value = true;
  }
};

const handleBrandClose = () => {
  brandDrawer.value = false;// 轮播图的取消
};

const handleCardVisibleClose = () => {
  cardDrawer.value = false;// 卡片链接的取消
};
// 卡片链接的取消
const handleCategoryVisibleClose = () => {
  categoryDrawer.value = false;
};

// 商品分组的取消
const handleProductVisibleClose = () => {
  productDrawer.value = false;
};
// 品牌推荐的取消
const handleCarouselVisibleClose = () => {
  carouselDrawer.value = false;
};
// 自定义模块的取消
const handleCustomVisibleClose = () => {
  customDrawer.value = false;
};
// 添加模块
const handleModule = () => {
  proxy.$refs["moduleFormRef"].validate((valid) => {
    if (!valid) return;
    if (modalForm.value.moduleType !== "Banner" && modalForm.value.moduleType !== "Custom") {
      if (!proxy.publicArray(modalForm.value.descriptions))
        return proxy.$modal.msgError("请完整填写多语言");
    }
    if (disabledType.value) {
      site.module
        .sitewebsitemoduleUpdate({
          pathParams: {
            id: publicItem.value.id,
          },
          data: modalForm.value,
        })
        .then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess("修改成功");
            dialogVisible.value = false;
            handleClose();
            getList();
          }
        });
    } else {
      modalForm.value.websiteId = Number(route.query.id);
      site.module
        .sitewebsitemoduleAdd({
          data: modalForm.value,
        })
        .then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess("添加成功");
            dialogVisible.value = false;
            handleClose();
            getList();
          }
        });
    }
  });
};
// 取消模块
const handleClose = () => {
  disabledType.value = false;
  proxy.resetForm("moduleFormRef");
  dialogVisible.value = false;
  showLanguage.value = false;
  modalForm.value.descriptions = [];
  modalForm.value.moduleName = "";
  modalForm.value.websiteId = null;
  modalForm.value.status = 1;
  modalForm.value.moduleType = "Banner";
};
// 分页
const handlePageChange = (newPage) => {
  queryParams.value.pageNum = newPage.page;
  queryParams.value.pageSize = newPage.limit;
  getList();
};

// 表格状态控制
const handleStatusChange = (e) => {
  if (!Judgment.value) return;
  proxy.$modal
    .confirm("确定需要修改此状态吗？")
    .then(() => {
      site.module
        .sitewebsitemoduleUpdatestatus({
          pathParams: {
            id: e.id,
          },
          params: {
            status: e.status,
          },
        })
        .then((res) => {
          proxy.$modal.msgSuccess("修改状态成功");
          getList();
        });
    })
    .catch((err) => {
      if (e.status) {
        return (e.status = 0);
      } else {
        return (e.status = 1);
      }
    });
};
const handleModuleType = (val) => {
  console.log(val, '选中的类型');
  modalForm.value.descriptions = [];
  if (val == "Banner" || val == "Custom") {
    showLanguage.value = false;
  } else {
    getDetails();
    showLanguage.value = true;
  }
  if (val === "Card" || val === "Brand") {
    showRemark.value = true;
  } else {
    showRemark.value = false;
  }
};
const getDetails = () => {
  site.general
    .sitewebsiteGetbyid({
      pathParams: {
        id: Number(route.query.id),
      },
    })
    .then((res) => {
      res.data.languageIds.forEach((e) => {
        modalForm.value.descriptions.push({
          languageId: e,
          name: "",
          description: "",
        });
      });
      console.log(res.data.languageIds, "[[[]]]");
    });
};
const handleDrag = () => {
  const elTableBody = proxy.$refs["dragTable"].$el.querySelector(
    ".el-table__body-wrapper tbody"
  );
  proxy.Sortable.create(elTableBody, {
    animation: 150, // 拖拽动画
    handle: ".icon-handle", // 把手选择器
    filter: ".no-drag", // 禁用拖拽的类
    ghostClass: "blue-background-class",
    onEnd: (event) => {
      const { oldIndex, newIndex } = event;
      console.log(oldIndex, newIndex);
      // 调整数据顺序
      const movedItem = tableData.value.splice(oldIndex, 1)[0];
      tableData.value.splice(newIndex, 0, movedItem);
      site.module.sitewebsitemoduleUpdatemodulesort(
        {
          data: {
            websiteId: Number(route.query.id),
            moduleIds: tableData.value.map((item) => item.id)
          }
        }
      ).then(res => {
        if (res.code === 200) {
          tableData.value = []
          getList();
        }
      })
    },
  });
}
const incidentList = reactive([
  {
    title: "编辑",
    type: "primary",
  },
  {
    title: "设计",
    type: "primary",
  },
  {
    title: "删除",
    type: "danger",
  },
]);
const rules = {
  moduleName: [{ required: true, message: "请输入", trigger: "blur" }],
  moduleType: [{ required: true, message: "请选择", trigger: "blur" }],
};
const addModule = () => {
  dialogVisible.value = true
  disabledType.value = false
};
</script>
<style lang="scss" scoped>
.button_box {
  display: flex;
  flex-direction: column;
  gap: 40px;
  margin-bottom: 20px;

  >button {
    width: 100px;
  }
}
</style>